package struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.form.ActionForm;
import struts.form.FullForm;
import struts.form.XmlBean;

public class ActionServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2457288337361364012L;

	/**
	 * 
	 */

    
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		 /*得到请求参数值
		 把得到的请求参数值放入request中
		 得到一个请求转发器
		 通过转发器将request转入response中*/
		/* //String ss = request.getParameter("text");
		 Action action = new PandAction();
		 String url= action.execute(request);
		//servlet发出请求
		 RequestDispatcher rd = request.getRequestDispatcher(url);
		 rd.forward(request,response);*/
		//获得请求头
		 String path=(this.getPath(request.getServletPath()));
		 //得到Application,从中取出struts对象
		 Map<String,XmlBean> map = (Map<String,XmlBean>)this.getServletContext().getAttribute("struts");
		 //从struts对象中通过键值path得到XmlBean对象.
		 XmlBean xml = map.get(path);
		 //从XmlBean对象中取得类名字符串
		 String formclass = xml.getFormClass();
		 System.out.println("beanname:"+formclass);
		 //将类名字符串作为参数给Full,通过类名字符串反射得到这个类
		 ActionForm form = FullForm.Full(formclass,request);
		 String actiontype=xml.getActionClass();
		 Action action = null;
		 String url = "";
		 try{
			 Class<?> clazz = Class.forName(actiontype);
			 action = (Action) clazz.newInstance();
			 url = action.execute(request,response,form,xml.getActionForward());
		 }catch(Exception e){
			 e.printStackTrace();
			 System.out.println("严重:控制器异常！");
		 }
	     RequestDispatcher dis = request.getRequestDispatcher(url);
	     dis.forward(request,response);
	}
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
		this.doGet(request, response);
	}
    
    private String getPath(String servletpath){
    	return servletpath.split("\\.")[0];
    }
}
